1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package com.google.common.hash;
18
19 import com.google.caliper.BeforeExperiment;
20 import com.google.caliper.Benchmark;
21 import com.google.caliper.Param;
22 import com.google.common.hash.HashFunction;
23 import com.google.common.hash.Hashing;
24
25 import java.security.MessageDigest;
26 import java.security.NoSuchAlgorithmException;
27 import java.util.Random;
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42 public class MessageDigestAlgorithmBenchmark {
43 @Param({"10", "1000", "100000", "1000000"}) int size;
44 @Param Algorithm algorithm;
45 @Param HashMethod hashMethod;
46
47 private enum HashMethod {
48 MESSAGE_DIGEST_API() {
49 @Override public byte[] hash(Algorithm algorithm, byte[] input) {
50 MessageDigest md = algorithm.getMessageDigest();
51 md.update(input);
52 return md.digest();
53 }
54 },
55 HASH_FUNCTION_API() {
56 @Override public byte[] hash(Algorithm algorithm, byte[] input) {
57 return algorithm.getHashFunction().hashBytes(input).asBytes();
58 }
59 };
60 public abstract byte[] hash(Algorithm algorithm, byte[] input);
61 }
62
63 private enum Algorithm {
64 MD5("MD5", Hashing.md5()),
65 SHA_1("SHA-1", Hashing.sha1()),
66 SHA_256("SHA-256", Hashing.sha256()),
67 SHA_512("SHA-512", Hashing.sha512());
68
69 private final String algorithmName;
70 private final HashFunction hashFn;
71 Algorithm(String algorithmName, HashFunction hashFn) {
72 this.algorithmName = algorithmName;
73 this.hashFn = hashFn;
74 }
75 public MessageDigest getMessageDigest() {
76 try {
77 return MessageDigest.getInstance(algorithmName);
78 } catch (NoSuchAlgorithmException e) {
79 throw new AssertionError(e);
80 }
81 }
82 public HashFunction getHashFunction() {
83 return hashFn;
84 }
85 }
86
87
88 private static final int RANDOM_SEED = new Random().nextInt();
89
90 private byte[] testBytes;
91
92 @BeforeExperiment void setUp() {
93 testBytes = new byte[size];
94 new Random(RANDOM_SEED).nextBytes(testBytes);
95 }
96
97 @Benchmark byte hashing(int reps) {
98 byte result = 0x01;
99 HashMethod hashMethod = this.hashMethod;
100 Algorithm algorithm = this.algorithm;
101 for (int i = 0; i < reps; i++) {
102 result ^= hashMethod.hash(algorithm, testBytes)[0];
103 }
104 return result;
105 }
106 }